package com.whmskj.xjlhbc.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whmskj.xjlhbc.domain.*;
import com.whmskj.xjlhbc.dto.QueryDto;
import com.whmskj.xjlhbc.mapper.*;
import com.whmskj.xjlhbc.mobile.GetStartDate;
import com.whmskj.xjlhbc.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StatisticsOnTheDailyProductionOfServiceImpl
        extends ServiceImpl<StatisticsOnTheDailyProductionOfMapper, StatisticsOnTheDailyProductionOf> implements IStatisticsOnTheDailyProductionOfService {

    @Autowired
    private ISublistOfDailyAttendanceRecordsFService sublistOfDailyAttendanceRecordsFService;

    @Autowired
    private ThePlanesStrappedToATableMapper thePlanesStrappedToATableMapper;

    @Autowired
    private IStatisticsService statisticsService;

    @Autowired
    private MeszjjLzMapper meszjjLzMapper;

    @Autowired
    private MesjsjLzMapper mesjsjLzMapper;

    @Autowired
    private IStatisticsDayZjService statisticsDayZjService;

    @Autowired
    private IStatisticsDayJsService statisticsDayJsService;

    @Autowired
    private Bchb06cpcmrjdbMapper bchb06cpcmrjdbMapper;

    @Override
    public List<SublistOfDailyAttendanceRecordsF> queryList(QueryDto param) {
        List<String> className = getClassName();
        if(className.isEmpty()){
            return new ArrayList<>();
        }
        param.setHasJth(true);
        List<SublistOfDailyAttendanceRecordsF> list = sublistOfDailyAttendanceRecordsFService.queryList(param);
        LambdaQueryWrapper<Statistics> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Statistics::getDateymd, param.getDateOfAttendance());
        wrapper.in(Statistics::getClassname, className);
        List<Statistics> statisticsList = statisticsService.list(wrapper);
        list.forEach(item->{
            if(item.getJthList().isEmpty())return;
            List<Statistics> filterList = statisticsList.stream().filter(f -> item.getJthList().contains(f.getMacid()) && item.getClassesInTheClassroom().contains(f.getClassname())).collect(Collectors.toList());
            double sum = filterList.stream().mapToDouble(s -> NumberUtil.parseDouble(s.getClothlength())).sum();
            double zbsum = filterList.stream().mapToDouble(s -> NumberUtil.parseDouble(s.getClothlength_zb())).sum();
            double xl = filterList.stream().mapToDouble(s -> NumberUtil.parseDouble(s.getEfficiency())).average().orElse(0.0);
            item.setCl(String.format("%.2f",sum));
            item.setZbCl(String.format("%.2f",zbsum));
            item.setXl(String.format("%.2f",xl));
        });
        return list;
    }

    private List<String> getClassName(){
        List<String> className = getClassName1();
        return className.stream().map(item -> item.contains("甲") ? "甲" : item.contains("乙") ? "乙" : item).collect(Collectors.toList());
    }

    private List<String> getClassName1(){
        return sublistOfDailyAttendanceRecordsFService.getClassName();
    }

    @Override
    public List<Sc18dDailyClassProductionStatist> tjList() {
        List<String> className = getClassName();
        if(className.isEmpty()){
            return new ArrayList<>();
        }
        QueryDto param = new QueryDto();
        param.setHasJth(true);
        List<DailyAttendanceLogMasterTable> list = sublistOfDailyAttendanceRecordsFService.tjList(param);
        List<String> dates = list.stream().map(DailyAttendanceLogMasterTable::getDateOfAttendance).collect(Collectors.toList());
        LambdaQueryWrapper<Statistics> statisticsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        statisticsLambdaQueryWrapper.in(Statistics::getClassname, className).in(Statistics::getDateymd,dates);
        List<Statistics> statisticsList = statisticsService.list(statisticsLambdaQueryWrapper);
        List<String> dateOfAttendanceList = list.stream().map(DailyAttendanceLogMasterTable::getDateOfAttendance).collect(Collectors.toList());
        LambdaQueryWrapper<ThePlanesStrappedToATable> thePlanesStrappedToATableLambdaQueryWrapper = new LambdaQueryWrapper<>();
        thePlanesStrappedToATableLambdaQueryWrapper.in(ThePlanesStrappedToATable::getF7ba, dateOfAttendanceList)
                .isNotNull(ThePlanesStrappedToATable::getNumberOfStations)
                .in(ThePlanesStrappedToATable::getClass1, getClassName1())
                .ne(ThePlanesStrappedToATable::getNumberOfStations, 0);
        List<ThePlanesStrappedToATable> thePlanesStrappedToATables = thePlanesStrappedToATableMapper.selectList(thePlanesStrappedToATableLambdaQueryWrapper);
        return list.stream().map(item -> {
            List<Statistics> filterList = statisticsList.stream().filter(f -> f.getDateymd().equals(item.getDateOfAttendance()) && item.getClasses66().contains(f.getClassname())).collect(Collectors.toList());
            Sc18dDailyClassProductionStatist sc18dDailyClassProductionStatist = new Sc18dDailyClassProductionStatist();
            long totalJt = filterList.stream().map(Statistics::getMacid).distinct().count();
            double sum = filterList.stream().mapToDouble(m->NumberUtil.parseDouble(m.getClothlength(),0.0)).sum();
            double zbsum = filterList.stream().mapToDouble(m->NumberUtil.parseDouble(m.getClothlength_zb(),0.0)).sum();
            double avg = filterList.stream().mapToDouble(m->NumberUtil.parseDouble(m.getEfficiency(),0.0)).average().orElse(0.0);
            sc18dDailyClassProductionStatist.setZbCl(String.format("%.2f", zbsum));
            sc18dDailyClassProductionStatist.setEfficiency(String.format("%.2f", avg));
            sc18dDailyClassProductionStatist.setKts(totalJt);
            sc18dDailyClassProductionStatist.setProduction(String.format("%.2f", sum));
            sc18dDailyClassProductionStatist.setNumberOfPersonsInAttendance(thePlanesStrappedToATables.stream().filter(f-> f.getF7ba().equals(item.getDateOfAttendance()) && item.getClasses66().contains(f.getClass1())).count());
            sc18dDailyClassProductionStatist.setClass554(item.getClasses66());
            sc18dDailyClassProductionStatist.setStatisticsDate(item.getDateOfAttendance());
            sc18dDailyClassProductionStatist.setClasses(item.getClasses());
            return sc18dDailyClassProductionStatist;
        }).filter(f-> f.getNumberOfPersonsInAttendance() > 0).collect(Collectors.toList());
    }

    @Override
    public List<Sc18dDailyClassProductionStatist> rclList(String startDate, String endDate) {
        LocalDate start = StringUtils.hasText(startDate) ? LocalDate.parse(startDate) : LocalDateTimeUtil.parseDate(GetStartDate.getMonthStartDate().substring(0,10));
        LocalDate end = StringUtils.hasText(endDate) ? LocalDate.parse(endDate) : LocalDate.now();
        end = end.isAfter(LocalDate.now()) ? LocalDate.now() : end;
        LambdaQueryWrapper<Statistics> statisticsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        statisticsLambdaQueryWrapper.between(Statistics::getDateymd, start.toString(),end.toString());
        List<Statistics> statisticsList = statisticsService.list(statisticsLambdaQueryWrapper);
        List<Sc18dDailyClassProductionStatist> list = new ArrayList<>();
        while(start.isBefore(end) || start.isEqual(end)){
            String dateymd = start.toString();
            List<Statistics> filterList = statisticsList.stream().filter(f -> f.getDateymd().equals(dateymd)).collect(Collectors.toList());
            Sc18dDailyClassProductionStatist sc18dDailyClassProductionStatist = new Sc18dDailyClassProductionStatist();
            long totalJt = filterList.stream().map(Statistics::getMacid).distinct().count();
            double sum = filterList.stream().mapToDouble(m->NumberUtil.parseDouble(m.getClothlength(),0.0)).sum();
            double zbsum = filterList.stream().mapToDouble(m->NumberUtil.parseDouble(m.getClothlength_zb(),0.0)).sum();
            double avg = filterList.stream().mapToDouble(m->NumberUtil.parseDouble(m.getEfficiency(),0.0)).average().orElse(0.0);
            sc18dDailyClassProductionStatist.setZbCl(String.format("%.2f", zbsum));
            sc18dDailyClassProductionStatist.setEfficiency(String.format("%.2f", avg));
            sc18dDailyClassProductionStatist.setKts(totalJt);
            sc18dDailyClassProductionStatist.setProduction(String.format("%.2f", sum));
            sc18dDailyClassProductionStatist.setStatisticsDate(dateymd);
            list.add(sc18dDailyClassProductionStatist);
            start = start.plusDays(1);
        }
        Collections.reverse(list);
        return list;
    }

    @Override
    public List<StatisticsOnTheDailyProductionOf> jtclList(String id) {
        SublistOfDailyAttendanceRecordsF sublistOfDailyAttendanceRecordsF = sublistOfDailyAttendanceRecordsFService.getById(id);
        String dateOfAttendance = sublistOfDailyAttendanceRecordsF.getDateOfAttendance();
        LambdaQueryWrapper<ThePlanesStrappedToATable> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ThePlanesStrappedToATable::getNameOfPersonnel, sublistOfDailyAttendanceRecordsF.getNameOfEmployee())
                .eq(ThePlanesStrappedToATable::getF7ba, dateOfAttendance).last("limit 1");
        ThePlanesStrappedToATable thePlanesStrappedToATable = thePlanesStrappedToATableMapper.selectOne(wrapper);
        List<String> jthList = new ArrayList<>();
        if(Objects.nonNull(thePlanesStrappedToATable)){
            jthList = Arrays.stream(thePlanesStrappedToATable.getF657().split(",")).collect(Collectors.toList());
        }
        if(jthList.isEmpty()){
            return new ArrayList<>();
        }
        String className = sublistOfDailyAttendanceRecordsF.getClassesInTheClassroom().contains("甲") ? "甲" : "乙";
        LambdaQueryWrapper<Statistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Statistics::getDateymd, dateOfAttendance);
        queryWrapper.in(Statistics::getMacid, jthList);
        queryWrapper.eq(Statistics::getClassname, className);
        queryWrapper.orderByAsc(Statistics::getMacid);
        List<Statistics> statisticsList = statisticsService.list(queryWrapper);
        return statisticsList.stream().map(s -> {
            StatisticsOnTheDailyProductionOf result = new StatisticsOnTheDailyProductionOf();
            result.setStationNumber(s.getMacid());
            result.setProductionAtThatDate(new BigDecimal(s.getClothlength()));
            result.setHasUpdate(s.getHasUpdate());
            result.setProductionVarieties(s.getVariety());
            result.setStatisticsDate(DateUtil.formatDateTime(s.getStartdatetime()));
            result.setId(s.getId());
            result.setRuntime_format(s.getRuntime_format());
            result.setUpdatetime(DateUtil.formatDateTime(s.getUpdatetime()));
            DateTime start = DateUtil.offsetHour(s.getStartdatetime(), 12);
            DateTime date = DateUtil.date();
            result.setClassesEnd(start.isBeforeOrEquals(date));
            return result;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean updateJtcl(StatisticsOnTheDailyProductionOf body) {
        Long id = body.getId();
        BigDecimal productionAtThatDate = body.getProductionAtThatDate();
        Statistics statistics = new Statistics();
        statistics.setId(id);
        statistics.setClothlength(productionAtThatDate.toString());
        statistics.setHasUpdate("1");
        return statisticsService.updateById(statistics);
    }

    @Override
    public Object bzdbList(DateTime start, DateTime end) {
        DateTime nowDate = DateUtil.date();
        end = nowDate.isBeforeOrEquals(end) ? nowDate : end;
        String startDate = start.toDateStr();
        String endDate = end.toDateStr();
        List<Map<String, Object>> list = baseMapper.selectBzdbList(startDate, endDate);
        long days = DateUtil.betweenDay(start, end, true);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for(int i=0;i<=days;i++){
            String date = end.toDateStr();
            List<Map<String, Object>> dataList = list.stream().filter(f -> date.equals(String.valueOf(f.get("statisticsDate")))).collect(Collectors.toList());
            Map<String, Object> map = new HashMap<>();
            map.put("date", date);
            map.put("list", dataList);
            resultList.add(map);
            end = end.offset(DateField.DAY_OF_MONTH, -1);
        }
        return resultList;
    }

    @Override
    public Object zjDay(QueryDto param) {
        String dateOfAttendance = param.getDateOfAttendance();
        String day = StringUtils.hasText(dateOfAttendance) ? dateOfAttendance + GetStartDate.hour9 : GetStartDate.getDayStartDate();
        DateTime start = DateUtil.parse(day);
        DateTime end = start.offsetNew(DateField.DAY_OF_MONTH, 1);
        LambdaQueryWrapper<MeszjjLz> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(MeszjjLz::getTs, start, end);
        List<MeszjjLz> meszjjLzList = meszjjLzMapper.selectList(wrapper);
        Map<String, List<MeszjjLz>> mapList = meszjjLzList.stream().collect(Collectors.groupingBy(MeszjjLz::getMacid));
        Set<Map.Entry<String, List<MeszjjLz>>> entries = mapList.entrySet();
        List<MeszjjLz> zjjList = new ArrayList<>();
        for (Map.Entry<String, List<MeszjjLz>> entry : entries) {
            String key = entry.getKey();
            List<MeszjjLz> list = entry.getValue();
            MeszjjLz meszjjLz = new MeszjjLz();
            meszjjLz.setMacid(key);
            meszjjLz.setMacname(list.get(0).getMacname());
            meszjjLz.setCurrentvalue(String.valueOf(list.stream().mapToLong(m -> NumberUtil.parseLong(m.getCurrentvalue(), 0L)).sum()));
            meszjjLz.setZs(String.valueOf(list.size()));
            zjjList.add(meszjjLz);
        }
        zjjList.sort(Comparator.comparing(MeszjjLz::getMacid));
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> topMap = new HashMap<>();
        topMap.put("cl", zjjList.stream().mapToLong(m -> NumberUtil.parseLong(m.getCurrentvalue(), 0L)).sum());
        topMap.put("kts", zjjList.size());
        topMap.put("lz", zjjList.stream().mapToLong(m -> NumberUtil.parseLong(m.getZs(), 0L)).sum());
        resultMap.put("list", zjjList);
        resultMap.put("top", topMap);
        return resultMap;
    }
    @Override
    public Object zjDayDetail(QueryDto param) {
        String dateOfAttendance = param.getDateOfAttendance();
        String day = StringUtils.hasText(dateOfAttendance) ? dateOfAttendance + GetStartDate.hour9 : GetStartDate.getDayStartDate();
        DateTime start = DateUtil.parse(day);
        DateTime end = start.offsetNew(DateField.DAY_OF_MONTH, 1);
        LambdaQueryWrapper<MeszjjLz> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(MeszjjLz::getTs, start, end).eq(MeszjjLz::getMacid,param.getMacid());
        return meszjjLzMapper.selectList(wrapper);
    }
    @Override
    public Object zjMonth(QueryDto param) {
        String dateOfAttendance = param.getDateOfAttendance();
        DateTime end;
        DateTime start;
        if(StringUtils.hasText(dateOfAttendance)){
            end = DateUtil.parse(dateOfAttendance + GetStartDate.day).offset(DateField.DAY_OF_MONTH,-1);
            start = end.offsetNew(DateField.MONTH, -1).offset(DateField.DAY_OF_MONTH, 1);
        }else{
            start = DateUtil.parse(GetStartDate.getMonthStartDate().substring(0, 10));
            end = start.offsetNew(DateField.MONTH, 1).offset(DateField.DAY_OF_MONTH, -1);
        }
        int month = end.month()+1;
        int year = end.year();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> defaultMap = new HashMap<>();
        defaultMap.put("cl", 0);
        defaultMap.put("ycl", 0);
        defaultMap.put("lz",0);
        Map<String, Object> topMap = Optional.ofNullable(baseMapper.selectZjClMonth(year, month)).orElse(defaultMap);
        List<Map<String, Object>> list = baseMapper.selectZjClList(start.toDateStr(), end.toDateStr());
        BigDecimal bigDecimal = Optional.ofNullable((BigDecimal) topMap.get("cumulativeProduction")).orElse(BigDecimal.ZERO);
        defaultMap.put("cl", !list.isEmpty() ? bigDecimal.doubleValue()/list.size() : bigDecimal.doubleValue());
        defaultMap.put("ycl", bigDecimal.doubleValue());
        defaultMap.put("lz", Optional.ofNullable(topMap.get("numberOfLandingAxes")).orElse(0));
        resultMap.put("top", defaultMap);
        resultMap.put("list", list);
        return resultMap;
    }

    @Override
    public Object zjYear(QueryDto param) {
        int year = StringUtils.hasText(param.getDateOfAttendance()) ? NumberUtil.parseInt(param.getDateOfAttendance().substring(0,4), 2025) : LocalDate.now().getYear();
        LambdaQueryWrapper<StatisticsDayZj> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(StatisticsDayZj::getDateymd, year);
        List<StatisticsDayZj> statisticsDayZjList = statisticsDayZjService.list(wrapper);
        List<StatisticsDayZj> resultList = new ArrayList<>();
        int monthValue = LocalDate.now().getMonthValue();
        for(int i=monthValue;i>0;i--){
            String str = year+"-"+StrUtil.padPre(String.valueOf(i), 2, "0");
            List<StatisticsDayZj> list = statisticsDayZjList.stream().filter(f -> f.getDateymd().startsWith(str)).collect(Collectors.toList());
            StatisticsDayZj statisticsDayZj = new StatisticsDayZj();
            statisticsDayZj.setDateymd(str);
            statisticsDayZj.setZs(String.valueOf(list.stream().mapToInt(m -> NumberUtil.parseInt(m.getZs(), 0)).sum()));
            statisticsDayZj.setClothlength(String.valueOf(list.stream().mapToLong(m -> NumberUtil.parseLong(m.getClothlength(), 0L)).sum()));
            resultList.add(statisticsDayZj);
        }
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> topMap = new HashMap<>();
        long sum = resultList.stream().mapToLong(m -> NumberUtil.parseLong(m.getClothlength(), 0L)).sum();
        double ycl = !resultList.isEmpty() ? (double) sum /resultList.size() : sum;
        topMap.put("cl", sum);
        topMap.put("ycl", String.format("%.2f",ycl));
        topMap.put("lz", resultList.stream().mapToLong(m -> NumberUtil.parseLong(m.getZs(), 0L)).sum());
        resultMap.put("list", resultList);
        resultMap.put("top", topMap);
        return resultMap;
    }

    @Override
    public Object jsDay(QueryDto param) {
        String dateOfAttendance = param.getDateOfAttendance();
        String day = StringUtils.hasText(dateOfAttendance) ? dateOfAttendance + GetStartDate.hour9 : GetStartDate.getDayStartDate();
        DateTime start = DateUtil.parse(day);
        DateTime end = start.offsetNew(DateField.DAY_OF_MONTH, 1);
        LambdaQueryWrapper<MesjsjLz> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(MesjsjLz::getTs, start, end);
        List<MesjsjLz> mesjsjLzList = mesjsjLzMapper.selectList(wrapper);
        Map<String, List<MesjsjLz>> mapList = mesjsjLzList.stream().collect(Collectors.groupingBy(MesjsjLz::getMacid));
        Set<Map.Entry<String, List<MesjsjLz>>> entries = mapList.entrySet();
        List<MesjsjLz> jsjList = new ArrayList<>();
        for (Map.Entry<String, List<MesjsjLz>> entry : entries) {
            String key = entry.getKey();
            List<MesjsjLz> list = entry.getValue();
            MesjsjLz mesjsjLz = new MesjsjLz();
            mesjsjLz.setMacid(key);
            mesjsjLz.setMacname(list.get(0).getMacname());

            // 过滤掉currentvalue小于100的数据
            List<MesjsjLz> filteredList = list.stream()
                    .filter(m -> m.getCurrentvalue().compareTo(new BigDecimal("100")) >= 0)
                    .collect(Collectors.toList());

            // 计算过滤后的产量总和，保留小数位
            BigDecimal sum = filteredList.stream()
                    .map(MesjsjLz::getCurrentvalue)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            mesjsjLz.setCurrentvalue(sum);

            // lz数只统计currentvalue大于等于100的记录数
            mesjsjLz.setZs(String.valueOf(filteredList.size()));
            jsjList.add(mesjsjLz);
        }
        jsjList.sort(Comparator.comparing(MesjsjLz::getMacid));
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> topMap = new HashMap<>();

        // 总产量和总lz数也只统计currentvalue大于等于100的记录
        BigDecimal totalCl = jsjList.stream()
                .map(MesjsjLz::getCurrentvalue)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        long totalLz = jsjList.stream()
                .mapToLong(m -> Long.parseLong(m.getZs()))
                .sum();

        topMap.put("cl", totalCl.toString());
        topMap.put("kts", jsjList.size());
        topMap.put("lz", totalLz);
        resultMap.put("list", jsjList);
        resultMap.put("top", topMap);
        return resultMap;
    }


    @Override
    public Object jsDayDetail(QueryDto param) {
        String dateOfAttendance = param.getDateOfAttendance();
        String day = StringUtils.hasText(dateOfAttendance) ? dateOfAttendance + GetStartDate.hour9 : GetStartDate.getDayStartDate();
        DateTime start = DateUtil.parse(day);
        DateTime end = start.offsetNew(DateField.DAY_OF_MONTH, 1);
        LambdaQueryWrapper<MesjsjLz> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(MesjsjLz::getTs, start, end).eq(MesjsjLz::getMacid,param.getMacid());
        return mesjsjLzMapper.selectList(wrapper);
    }

    @Override
    public Object jsMonth(QueryDto param) {
        String dateOfAttendance = param.getDateOfAttendance();
        DateTime end;
        DateTime start;
        if(StringUtils.hasText(dateOfAttendance)){
            end = DateUtil.parse(dateOfAttendance + GetStartDate.day).offset(DateField.DAY_OF_MONTH,-1);
            start = end.offsetNew(DateField.MONTH, -1).offset(DateField.DAY_OF_MONTH, 1);
        }else{
            start = DateUtil.parse(GetStartDate.getMonthStartDate().substring(0, 10));
            end = start.offsetNew(DateField.MONTH, 1).offset(DateField.DAY_OF_MONTH, -1);
        }
        int month = end.month()+1;
        int year = end.year();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> defaultMap = new HashMap<>();
        defaultMap.put("cl", 0);
        defaultMap.put("ycl", 0);
        defaultMap.put("lz",0);
        Map<String, Object> topMap = Optional.ofNullable(baseMapper.selectJsClMonth(year, month)).orElse(defaultMap);
        List<Map<String, Object>> list = baseMapper.selectJsClList(start.toDateStr(), end.toDateStr());
        BigDecimal bigDecimal = Optional.ofNullable((BigDecimal) topMap.get("cumulativeProduction")).orElse(BigDecimal.ZERO);
        defaultMap.put("cl", !list.isEmpty() ? bigDecimal.doubleValue()/list.size() : bigDecimal.doubleValue());
        defaultMap.put("ycl", bigDecimal.doubleValue());
        defaultMap.put("lz", Optional.ofNullable(topMap.get("numberOfLandingAxes")).orElse(0));
        resultMap.put("top", defaultMap);
        resultMap.put("list", list);
        return resultMap;
    }

    @Override
    public Object jsYear(QueryDto param) {
        int year = StringUtils.hasText(param.getDateOfAttendance()) ? NumberUtil.parseInt(param.getDateOfAttendance().substring(0,4), 2025) : LocalDate.now().getYear();
        LambdaQueryWrapper<StatisticsDayJs> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(StatisticsDayJs::getDateymd, year);
        List<StatisticsDayJs> statisticsDayJsList = statisticsDayJsService.list(wrapper);
        List<StatisticsDayJs> resultList = new ArrayList<>();
        int monthValue = LocalDate.now().getMonthValue();
        for(int i=monthValue;i>0;i--){
            String str = year+"-"+StrUtil.padPre(String.valueOf(i), 2, "0");
            List<StatisticsDayJs> list = statisticsDayJsList.stream().filter(f -> f.getDateymd().startsWith(str)).collect(Collectors.toList());
            StatisticsDayJs statisticsDayJs = new StatisticsDayJs();
            statisticsDayJs.setDateymd(str);
            statisticsDayJs.setZs(String.valueOf(list.stream().mapToInt(m -> NumberUtil.parseInt(m.getZs(), 0)).sum()));
            statisticsDayJs.setClothlength(String.valueOf(list.stream().mapToLong(m -> NumberUtil.parseLong(m.getClothlength(), 0L)).sum()));
            resultList.add(statisticsDayJs);
        }
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> topMap = new HashMap<>();
        long sum = resultList.stream().mapToLong(m -> NumberUtil.parseLong(m.getClothlength(), 0L)).sum();
        double ycl = !resultList.isEmpty() ? (double) sum /resultList.size() : sum;
        topMap.put("cl", sum);
        topMap.put("ycl", String.format("%.2f",ycl));
        topMap.put("lz", resultList.stream().mapToLong(m -> NumberUtil.parseLong(m.getZs(), 0L)).sum());
        resultMap.put("list", resultList);
        resultMap.put("top", topMap);
        return resultMap;
    }

    @Override
    public Object zlCl(String month) {
        String start = GetStartDate.getMonthStartDate().substring(0,10);
        String end = DateUtil.today();
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(month)){
            LocalDate ld = LocalDate.parse(month+"-21").minusMonths(1);
            start = ld.withDayOfMonth(21).toString();
            end = LocalDate.parse(month+"-20").toString();
        }
        List<Bchb06cpcmrjdb> list = bchb06cpcmrjdbMapper.queryGroupByTjdate(start,end);
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> topMap = new HashMap<>();
        double sum = list.stream().mapToLong(Bchb06cpcmrjdb::getMbdrcl).sum();
        double sum1 = list.stream().mapToLong(Bchb06cpcmrjdb::getPjdrcl).sum();
        topMap.put("mb", sum);
        topMap.put("pj", sum1);
        result.put("top", topMap);
        result.put("tableList", list);
        return result;
    }

}
